package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.RequisitionDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.WorkHour;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class CheckOutFragment extends CheckDetailFragment {
  //	protected static final int REQUEST_PLAN_DATE_START = 0;
  protected static final int REQUEST_ACTUAL_DATE_END = 1;
  protected static final int REQUEST_ACTUAL_DATE_START = 2;
  //	protected static final int REQUEST_PLAN_DATE_END = 3;
  //	public static final int REQUEST_HOLY_TYPE = 5;

  private EditText mEtReason;
  private TextView mTvActualStartTime;
  private TextView mTvActualEndTime;
  private TextView mTvBeginTimeTitle;
  private TextView mTvEndTimeTitle;
  private TextView mTv0utHours;
  private EditText mEtActualHours;
  private String actOutDays = "";
  private RadioButton mRbApplyOut;
  private RadioButton mRbSupplyOut;
  private String mIfLaterWriter = "F";//是否补填,默认为申请F，不补填

  /**
   * Find the Views in the layout<br />
   * <br />
   * Auto-created on 2015-12-10 12:17:30 by Android Layout Finder
   * (http://www.buzzingandroid.com/tools/android-layout-finder)
   */
  private void findViews(View v) {

    mEtReason = (EditText) v.findViewById(R.id.et_overTimeReason_checkOver);
    //		mTvPlanStartTime = (TextView) v.findViewById(R.id.tv_planBeginTime_checkOver);
    //		mTvPlanEndTime = (TextView) v.findViewById(R.id.tv_planEndTime_checkOver);
    //		mEtPlanHours = (EditText) v.findViewById(R.id.et_planOverTimeHours_checkOver);
    //		mCbExtra = (CheckBox) v.findViewById(R.id.cb_isFillInExtra_checkOver);

    RadioGroup mRgOut = (RadioGroup) v.findViewById(R.id.rg_type);
    mRbApplyOut = (RadioButton) v.findViewById(R.id.rb_apply);
    mRbSupplyOut = (RadioButton) v.findViewById(R.id.rb_supply);
    mRbApplyOut.setText(R.string.applyOut);
    mRbSupplyOut.setText(R.string.supplyOut);

    mTvBeginTimeTitle = (TextView) v.findViewById(R.id.tv_beginTimeTitle);
    mTvEndTimeTitle = (TextView) v.findViewById(R.id.tv_endTimeTitle);
    mTvActualStartTime = (TextView) v.findViewById(R.id.tv_actualBeginTime_checkOver);
    mTvActualEndTime = (TextView) v.findViewById(R.id.tv_actualEndTime_checkOver);
    mEtActualHours = (EditText) v.findViewById(R.id.et_actualOverTimeHours_checkOver);
    mTv0utHours = (TextView) v.findViewById(R.id.tv_outHours);
    //		mEtPlanDays = (EditText) v.findViewById(R.id.et_planHolyDays_checkHoly);

    //		mEtActualDays = (EditText) v.findViewById(R.id.et_naturalHolyDays_checkHoly);

    //		mTvPlanStartTime.setOnClickListener(new OnClickListener() {
    //			@Override
    //			public void onClick(View v) {
    //				showDialog(mTvPlanStartTime.getText().toString().trim(), R.string.chooseTime, REQUEST_PLAN_DATE_START);
    //			}
    //
    //		});
    //
    //		mTvPlanEndTime.setOnClickListener(new OnClickListener() {
    //			@Override
    //			public void onClick(View v) {
    //				showDialog(mTvPlanEndTime.getText().toString().trim(), R.string.chooseTime, REQUEST_PLAN_DATE_END);
    //			}
    //		});
    mTvActualStartTime.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //				if (!mCbExtra.isChecked()) {
        //					Toast.makeText(getActivity(), R.string.noSelectExtra, Toast.LENGTH_SHORT).show();

        //					return;
        //				}
        showDialog(mTvActualStartTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_START);
      }
    });
    mTvActualEndTime.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //				if (!mCbExtra.isChecked()) {
        //					Toast.makeText(getActivity(), R.string.noSelectExtra, Toast.LENGTH_SHORT).show();
        //					return;
        //				}
        showDialog(mTvActualEndTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_END);
      }
    });
    //		mCbExtra.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    //
    //			@Override
    //			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    //				// 服务器回传的选中状态,不更新实际时间.否则会覆盖掉服务器回传的数据.
    //				if (ignoreChange) {
    //
    //					return;
    //				}

    //				if (isChecked) {

    //					mTvActualStartTime.setText(mTvPlanStartTime.getText());
    //					mTvActualEndTime.setText(mTvPlanEndTime.getText());
    //					mEtActualHours.setText(mEtPlanHours.getText());
    //					mEtActualDays.setText(mEtPlanDays.getText());

    //				} else {
    //				}
    //					mTvActualStartTime.setText("");
    //					mTvActualEndTime.setText("");
    //					mEtActualHours.setText("");
    //					mEtActualDays.setText("");
    //				LogUtil.i("userCha nge");
    //
    //			}
    //		});

    if (mMenuType == WAIT_CHECK || mMenuType == CHECK_PASS) {
      mEtReason.setEnabled(false);
      mTvActualStartTime.setEnabled(false);
      mTvActualStartTime.setEnabled(false);
      mTvActualEndTime.setEnabled(false);
      mEtActualHours.setEnabled(false);
      mRbApplyOut.setEnabled(false);
      mRbSupplyOut.setEnabled(false);
      //			mEtActualDays.setEnabled(false);
    }

    mRgOut.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          //申请
          case R.id.rb_apply:
            mIfLaterWriter = "F";
            break;
          //补填
          case R.id.rb_supply:
            mIfLaterWriter = "T";
            break;
          default:
            break;
        }
        initRadio(mIfLaterWriter);
      }
    });
  }

  /**
   * 初始化RadioGroup
   */
  private void initRadio(String ifLaterWriter) {

    if ("F".equalsIgnoreCase(ifLaterWriter)) {
      //申请
      mTvBeginTimeTitle.setText(R.string.planBeginTime);
      mTvEndTimeTitle.setText(R.string.planEndTime);
      mTvActualStartTime.setHint(R.string.planBeginTimeHint);
      mTvActualEndTime.setHint(R.string.planEndTimeHint);
      mTvActualEndTime.setHint(R.string.planEndTimeHint);
      mTv0utHours.setText(R.string.planOutHours);
    }
    if ("T".equalsIgnoreCase(ifLaterWriter)) {
      //补填
      mTvBeginTimeTitle.setText(R.string.actualBeginTime);
      mTvEndTimeTitle.setText(R.string.actualEndTime);
      mTvActualStartTime.setHint(R.string.actualBeginTimeHint);
      mTvActualEndTime.setHint(R.string.actualEndTimeHint);
      mTv0utHours.setText(R.string.actualOutHours);
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    setTitleCustom(R.string.requisitionout);// 1.更改标题.
    View view = inflater.inflate(R.layout.fragment_check_out, container, false);
    findViews(view);
    laterViewVisiblity(view, ifAllowSupplement);
    initDetailData();
    return view;
  }

  private void initDetailData() {
    if (mMenuType != ADD) {

      volleypostInit();
    }
  }

  private void volleypostInit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("attendType", mType);
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String response) {
        MyUtils.dismissDialog();
        try {
          RequisitionDetail requisitionDetail =
              new Gson().fromJson(response, RequisitionDetail.class);

          mEtReason.setText(requisitionDetail.getOutworkReason());
          mTvActualStartTime.setText(requisitionDetail.getPlanSTime());
          mTvActualEndTime.setText(requisitionDetail.getPlanETime());
          mEtActualHours.setText(requisitionDetail.getPanOutNum());
          mIfLaterWriter = requisitionDetail.getIfLaterWrite();
          if ("T".equalsIgnoreCase(mIfLaterWriter)) {
            mRbSupplyOut.setChecked(true);
          }
          if ("F".equalsIgnoreCase(mIfLaterWriter)) {
            mRbApplyOut.setChecked(true);
          }
          initRadio(mIfLaterWriter);

          //					mEtActualDays.setText(requisitionDetail.getActOutDays());
          //					mEtPlanDays.setText(requisitionDetail.getPlanOutDays());
          //					ignoreChange = true;
          //					mTvPlanStartTime.setText(requisitionDetail.getPlanSTime());
          //					mTvPlanEndTime.setText(requisitionDetail.getPlanETime());
          //					mEtPlanHours.setText(requisitionDetail.getPanOutNum());
          //					mCbExtra.setChecked(requisitionDetail.isIfLaterWrite());// 4.是否补填.
          //					ignoreChange = false;
          // et_naturalTripDays_checkTrip.setText(requisitionDetail
          // .getNaturalDays());// 5.自然天数.

        } catch (JsonSyntaxException e) {
          LogUtil.e("error", e);

          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.noConnectionToServer);
      }
    });
  }

  private void showDialog(String startDate, int titleId, int requestCode) {
    Date date = DateUtil.stringToDate(startDate);
    if (null == date) {
      date = new Date();
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(date, titleId);
    dialog.setTargetFragment(CheckOutFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    String startDate;// 开始时间
    String endDate;// 结束时间

    //		// 更新
    //		if (requestCode == REQUEST_PLAN_DATE_START) {
    //
    //			Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
    //
    //			String dateString = DateUtil.dateToString(resultData);

    //			mTvPlanStartTime.setText(dateString);
    //			startDate = mTvPlanStartTime.getText().toString().trim();
    //			endDate = mTvPlanEndTime.getText().toString().trim();
    // 获取工时
    //			getWorkHours(requestCode, startDate, endDate);

    //		}
    //		if (requestCode == REQUEST_PLAN_DATE_END) {
    //
    //			Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
    //
    //			String dateString = DateUtil.dateToString(resultData);

    //			mTvPlanEndTime.setText(dateString);
    //			startDate = mTvPlanStartTime.getText().toString().trim();
    //			endDate = mTvPlanEndTime.getText().toString().trim();
    // 获取工时
    //			getWorkHours(requestCode, startDate, endDate);
    //
    //		}
    if (requestCode == REQUEST_ACTUAL_DATE_START) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualStartTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_ACTUAL_DATE_END) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualEndTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(TYPE_RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private void getWorkHours(final int requestCode, String startTime, String endTime) {

    if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
      return;
    }
    if (DateUtil.before(endTime, startTime)) {
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_WORKHOUR);// 6.计算外出天数.
    HashMap<String, String> params = new HashMap<>();
    String jobNumber = CurrentUser.newInstance(getActivity()).getJobNumber();
    params.put("jobno", jobNumber);
    params.put("startDate", startTime);
    params.put("endDate", endTime);
    params.put("ifSimpleDivide", "true");
    MyUtils.showDialogLoading(getActivity(), R.string.loadingWorkHour);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        MyUtils.dismissDialog();
        try {
          WorkHour workHour = new Gson().fromJson(arg0, WorkHour.class);
          if (workHour.getResult() == 1) {
            String days = workHour.getMessage().getDays() + "";// 6.计算差旅天数.
            String hours = workHour.getMessage().getHours() + "";
            actOutDays = days;
            if (requestCode == REQUEST_ACTUAL_DATE_START
                || requestCode == REQUEST_ACTUAL_DATE_END) {
              mEtActualHours.setText(hours);
              //							mEtActualDays.setText(days);
            }
          } else if (workHour.getResult() == 0) {
            ToastUtil.show("未找到当前人员所属考勤分组,请联系管理员核实!");
          }
        } catch (Exception e) {
          LogUtil.e("workTimeOverError=" + e, e);
          ToastUtil.show("未找到当前人员所属考勤分组,请联系管理员核实!");
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
      }
    });
  }

  @Override public boolean isCorrectInput() {
    // 验证文本信息
    //		String planBeginTime = mTvPlanStartTime.getText().toString().trim();
    //		String planHours = mEtPlanHours.getText().toString().trim();
    //		String planEndTime = mTvPlanEndTime.getText().toString().trim();
    String reasonString = mEtReason.getText().toString().trim();
    String actualBeginTime = mTvActualStartTime.getText().toString().trim();
    String actualEndTime = mTvActualEndTime.getText().toString().trim();
    String outHours = mTv0utHours.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      ToastUtil.show(R.string.no_content);
      return false;
    }

    if (TextUtils.isEmpty(actualEndTime)) {
      ToastUtil.show(R.string.choseEndDate);
      return false;
    }
    if (TextUtils.isEmpty(actualBeginTime)) {
      ToastUtil.show(R.string.choseBeginDate);
      return false;
    }
    //		if (!TextUtils.isEmpty(actualEndTime) && DateUtil.before(currentTime, actualEndTime)) {
    //			ToastUtil.show(R.string.realEndTimeBdforeCurrent);
    //			return false;
    //		}
    //		if (!TextUtils.isEmpty(actualBeginTime) && DateUtil.before(currentTime, actualBeginTime)) {
    //			ToastUtil.show(R.string.realStartTimeBeforeCurrent);
    //			return false;
    //		}
    if (!DateUtil.before(actualBeginTime, actualEndTime)) {
      ToastUtil.show(R.string.realEndTimeAfterRealStartTime);
      return false;
    }
    if (TextUtils.isEmpty(outHours)) {
      ToastUtil.show(R.string.no_out_hours);
      return false;
    }

    return true;
  }

  @Override public void volleyPostSave(final String type) {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_SAVE_OR_RUN);

    HashMap<String, String> params = new HashMap<>();

    params.put("attendType", CheckDetailFragment.VALUE_OUT);
    params.put("saveOrRun", type);
    params.put("outworkReason", mEtReason.getText().toString().trim());
    params.put("planSTime", mTvActualStartTime.getText().toString().trim());
    params.put("planETime", mTvActualEndTime.getText().toString().trim());
    params.put("panOutNum", mEtActualHours.getText().toString().trim());
    //		params.put("planOutDays", mEtActualDays.getText().toString().trim());
    params.put("planOutDays", actOutDays);

    //		params.put("ifLaterWrite", "T");
    /**是否补填*/
    params.put("ifLaterWrite", mIfLaterWriter);
    if ("T".equalsIgnoreCase(mIfLaterWriter)) {
      params.put("actSTime", mTvActualStartTime.getText().toString().trim());
      params.put("actETime", mTvActualEndTime.getText().toString().trim());
      params.put("actOutNum", mEtActualHours.getText().toString().trim());
      //		params.put("actOutDays", mEtActualDays.getText().toString().trim());
      params.put("actOutDays", actOutDays);
    }

    if (mMenuType != ADD) {
      params.put("id", mId);
      if (TYPE_RUN.equals(type)) {

        params.put("isList", "0");
      }
    }

    if ("abort".equalsIgnoreCase(mDataStatus)) {
      params.put("dataStatus", "new");
    }
    LogUtil.i("outParams=" + params.toString());

    if (TYPE_RUN.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    }
    if (TYPE_SAVE.equals(type)) {

      MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    }

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          switch (successType) {
            case "1":
              getActivity().setResult(Activity.RESULT_OK);
              ToastUtil.show(R.string.success_operation);
              getActivity().finish();
              break;
            case "0":
              showErrorDialog(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mType + "#" + mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.success_operation);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }
}
